import { defineStore } from "pinia";
import router, { resetRouter } from "@/router/index.ts";
import {
    constantRoutes,
    notFount,
    asyncRouters,
    rootRouter,
} from "@/router/routeMap.ts";
import { cloneDeep } from "lodash-es";
import { getMenusApi } from "@/api/loginApi/index.ts";
const testChildren = [
    {
        id: 110101,
        path: "/user/user_item_one/child_one",
        name: "userItemOneChildOne",
        meta: {
            title: "三级菜单1",
            isKeepAlive: false,
            isHidden: false,
            level: 3,
        },
        component: () =>
            import("@/views/user/itemOneChild/childOne.vue"),
    },
    {
        id: 110102,
        path: "/user/user_item_one/child_two",
        name: "userItemOneChildTwo",
        meta: {
            title: "三级菜单2",
            isKeepAlive: true,
            isHidden: false,
            level: 3,
        },
        component: () =>
            import("@/views/user/itemOneChild/childTwo.vue"),

    },
    {
        id: 110103,
        path: "/user/user_item_one/child_three",
        name: "userItemOneChildThree",
        meta: {
            title: "三级菜单3",
            isKeepAlive: true,
            isHidden: false,
            level: 3,
        },
        component: () =>
            import("@/views/user/itemOneChild/childThree.vue"),
    },
]
// 递归遍历路由，把有权限的路由遍历出来
const filterAsyncRoutes = (routes, idList) => {
    for (let i = 0, len = routes.length; i < len; i++) {
        const element = routes[i];
        if (idList.includes(element.name)) {
            if (element.children?.length) {
                // element.redirect = element.children[0].path;
                element.children = filterAsyncRoutes(element.children, idList);
            }
        } else {
            routes.splice(i, 1);
            len = routes.length; // 删除后，需要重新计算长度
            if (i < len) {
                i--; // 删除后，数组后面的会往前移动一位，故需减一，否则会跳过下一位
            }
        }
    }
    return routes;
};
// 根据权限过滤出路由并将其扁平化成一维数组（keepAlive时,根路径'/'的children必须是所有路由组成的一维数组）
const handleFlatRoutes = (permissionArray: any[]) => {
    const newAsyncRoutes = cloneDeep(asyncRouters);
    const flatList: any = [];
    const flatRoutes = (list: any[]) => {
        list.forEach((permissionItem: any) => {
            const { name, title: menuTile } = permissionItem;
            const target = newAsyncRoutes.find((routeItem: any) => routeItem.name === name);
            if (target) {
                const { path, meta, component } = target
                const { title, ...restParams } = meta
                // 根据后端数据修改对应路由的信息，比如title,icon等可使用后端返回的
                const routeObj = {
                    path,
                    name,
                    meta: { title: menuTile ?? title, ...restParams },
                    component,
                }
                flatList.push(routeObj)
            }
            if (permissionItem.children?.length) {
                flatRoutes(permissionItem.children)
            }
        })
    }
    flatRoutes(newAsyncRoutes)
    return flatList
}
export const usePermissionStore = defineStore("permissionStore", {
    state: () => {
        return {
            routes: [],
            addRoutes: [],
        };
    },
    getters: {},
    actions: {
        setRoutes(addRoutes: []) {
            this.addRoutes = addRoutes;
            this.routes = constantRoutes.concat(addRoutes);
        },
        generateRoutes(permissionArray: []) {
            const _this = this;
            const flatList = []
            const flatRoute = (list: any[]) => {
                list.forEach((item: any) => {
                    flatList.push(item)
                    if (item.children?.length) {
                        flatRoute(item.children)
                    }
                })
            }
            return new Promise((resolve) => {
                const routes = cloneDeep(asyncRouters);
                const ids = permissionArray.map((item: any) => item.name);
                const accessedRoutes = filterAsyncRoutes(routes, ids); // 过滤出有权限的路由
                flatRoute(accessedRoutes);
                // rootRouter.redirect = accessedRoutes[0].path;
                rootRouter.children = flatList; // 设置根路由的children，这是keep-alive的重点，将所有路由扁平化成一维数组作为根路径“/”的children
                _this.setRoutes(rootRouter); // 把有权限的路由塞到pinia中
                resetRouter(); // 重置路由
                const target = rootRouter.children[2]
                // target.children = testChildren
                const routeList = [rootRouter];
                // testChildren.forEach((route: any) => {
                //     router.addRoute(route); // 添加动态路由
                // });
                routeList.forEach((route: any) => {
                    router.addRoute(route); // 添加动态路由
                });
                // debugger
                router.addRoute('/', notFount); // 添加404
                resolve();
            });
        },
        getMenus(role: string) {
            const data = [
                { name: "home" },
                { name: "user" },
                {
                    name: "userItemOne", children: [
                        { name: "userItemOneChildOne" },
                        { name: "userItemOneChildTwo" },
                    ]
                },
                { name: "userItemTwo" }
            ]
            return new Promise((resolve, reject) => {
                const idList = data.map((item) => item.id);
                // this.generateRoutes(idList);
                this.generateRoutes(data);
                resolve()
            })
            // return getMenusApi({ role })
            //     .then((res) => {
            //         if (res.code === 200) {
            //             debugger
            //             const data = res.data;
            //             const idList = data.map((item) => item.id);
            //             this.generateRoutes(idList);
            //             // this.setMenus(idList);
            //         }
            //     })
            //     .catch((err) => {
            //         return Promise.reject(err);
            //     });
        },
    },
    // persist: true, // true开启持久化，false关闭持久化
});
export default usePermissionStore;
